package com.lanju.dao;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.lanju.entity.Agreement;
import com.lanju.entity.User;

@Repository
public class AgreementDao extends BaseDao<Agreement, String> {

	private static final Log log = LogFactory.getLog(AgreementDao.class);
	@Autowired
	SessionFactory sessionFactory;

	@PersistenceContext(unitName = "financialmarketingUnit")
	private EntityManager entityManager;

	public void persist(Agreement transientInstance) {
		try {
			entityManager.persist(transientInstance);
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
	}

	public void remove(Agreement persistentInstance) {
		try {
			//entityManager.remove(persistentInstance);
			entityManager.remove(entityManager.merge(persistentInstance));
		} catch (RuntimeException re) {
			log.error("remove failed", re);
			throw re;
		}
	}

	public Agreement merge(Agreement detachedInstance) {
		try {
			Agreement result = entityManager.merge(detachedInstance);
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public Agreement getById(String id) {
		try {
			Agreement instance = entityManager.find(Agreement.class, id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	/** 根据参数获取, */
	@SuppressWarnings("unchecked")
	public Agreement getByParam(Agreement agreement) {
		try {
			StringBuffer sqld = new StringBuffer("from Agreement s where 1=1 ");
			
			if(!StringUtils.isEmpty(agreement.getAgreementType())){
				sqld.append(" and s.agreementType =:agreementType "); 
			}
			if(!StringUtils.isEmpty(agreement.getStatus())){
				sqld.append(" and s.status =:status "); 
			}
			if(!StringUtils.isEmpty(agreement.getSignUserId())){
				sqld.append(" and s.signUserId =:signUserId "); 
			}
			if(!StringUtils.isEmpty(agreement.getChargeUserId())){
				sqld.append(" and s.chargeUserId =:chargeUserId "); 
			}
			Query query = entityManager.createQuery(sqld.toString());
			if(!StringUtils.isEmpty( agreement.getAgreementType() )){
                query.setParameter("agreementType", agreement.getAgreementType());
            }
			if(!StringUtils.isEmpty( agreement.getStatus() )){
                query.setParameter("status", agreement.getStatus());
            }
			if(!StringUtils.isEmpty(agreement.getSignUserId())){
                query.setParameter("signUserId", agreement.getSignUserId());
			}
			if(!StringUtils.isEmpty(agreement.getChargeUserId())){
                query.setParameter("chargeUserId", agreement.getChargeUserId());
			}
			List<Agreement> list = query.getResultList();
			if (list != null && list.size() > 0) {
				return list.get(0);
			} else {
				return null;
			}
		} catch (Exception e) {
			log.error("findByParam fail", e);
			throw e;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Map> getList(Map param, int pageSize, int offset) {
		try {
			StringBuffer sql = new StringBuffer(
			        "select a.*, h.houseName "
			                +" from lj_agreement a " 
			                +" left join lj_house h on a.houseId = h.houseId where 1=1 ");
			if (param.get("userIdFlag") != null && param.get("userIdFlag").toString().length()>0) {
				sql.append(" and a.status<>-1  ");
			}
			if (param.get("userId") != null && param.get("userId").toString().length()>0) { 
				String userId = param.get("userId").toString();
				sql.append(" and ( a.signUserId ='"+userId+"'   or   a.chargeUserId ='"+userId+"') ");
			}
			if (param.get("phone") != null  && param.get("phone").toString().length()>0) { 
				String phone = param.get("phone").toString();
				sql.append(" and ( a.chargePhone like '%"+ phone +"%'   or   a.signPhone like '%"+ phone +"%' ) ");
			}
			if (param.get("agreementName") != null  && param.get("agreementName").toString().length()>0) { 
				sql.append(" and a.agreementName like '%" + param.get("agreementName").toString() + "%' ");
			}
			if (param.get("signUserName") != null && param.get("signUserName").toString().length()>0) { 
				String name = param.get("signUserName").toString();
				sql.append(" and ( a.signUserName like '%"+ name +"%'   or   a.chargeUserName like '%"+ name +"%' ) ");
			}
			if (param.get("chargeUserName") != null  && param.get("chargeUserName").toString().length()>0) { 
				String name = param.get("chargeUserName").toString();
				sql.append(" and ( a.chargeUserName like '%"+ name +"%'   or   a.chargeUserName like '%"+ name +"%' ) ");
			}
			if (param.get("agreementType") != null  && param.get("agreementType").toString().length()>0) { 
				sql.append(" and a.agreementType ="+ param.get("agreementType").toString() );
			}
			if (param.get("status") != null  && param.get("status").toString().length()>0) { 
				sql.append(" and a.status ="+ param.get("status").toString() );
			}
			
			sql.append(" order by a.createTime desc ");
			SQLQuery query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());
			return query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).setFirstResult(offset)
			        .setMaxResults(pageSize).list();
		} catch (Exception e) {
			log.error("getAgreementList fail", e);
		}
		return null;
	}

	public long getListCount(Map param) {
		try {
			StringBuffer sql = new StringBuffer(
			        "select a.*, h.houseName "
			                +" from lj_agreement a " 
			                +" left join lj_house h on a.houseId = h.houseId where 1=1 ");
			if (param.get("userIdFlag") != null && param.get("userIdFlag").toString().length()>0) {
				sql.append(" and a.status<>-1  ");
			}
			if (param.get("userId") != null && param.get("userId").toString().length()>0) { 
				String userId = param.get("userId").toString();
				sql.append(" and ( a.signUserId ='"+userId+"'   or   a.chargeUserId ='"+userId+"') ");
			}
			if (param.get("phone") != null  && param.get("phone").toString().length()>0) { 
				String phone = param.get("phone").toString();
				sql.append(" and ( a.chargePhone like '%"+ phone +"%'   or   a.signPhone like '%"+ phone +"%' ) ");
			}
			if (param.get("agreementName") != null  && param.get("agreementName").toString().length()>0) { 
				sql.append(" and a.agreementName like '%" + param.get("agreementName").toString() + "%' ");
			}
			if (param.get("signUserName") != null && param.get("signUserName").toString().length()>0) { 
				String name = param.get("signUserName").toString();
				sql.append(" and ( a.signUserName like '%"+ name +"%'   or   a.chargeUserName like '%"+ name +"%' ) ");
			}
			if (param.get("chargeUserName") != null  && param.get("chargeUserName").toString().length()>0) { 
				String name = param.get("chargeUserName").toString();
				sql.append(" and ( a.chargeUserName like '%"+ name +"%'   or   a.chargeUserName like '%"+ name +"%' ) ");
			}
			if (param.get("agreementType") != null  && param.get("agreementType").toString().length()>0) { 
				sql.append(" and a.agreementType ="+ param.get("agreementType").toString() );
			}
			if (param.get("status") != null  && param.get("status").toString().length()>0) { 
				sql.append(" and a.status ="+ param.get("status").toString() );
			}

			SQLQuery query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());
			
			return query.list().size();
			// return (long) query.getSingleResult();
		} catch (Exception e) {
			log.error("getList fail", e);
		}
		return 0;
	}

	
	
	public List<Map<String, Object>> getHouseList(Map<String, Object> param) {
		   try {
			   StringBuffer sql = new StringBuffer("select h.*, a.chargeUserName  from  lj_agreement a  join  lj_house h  on a.houseId = h.houseId  and a.agreementType = 1  and a.status = 1 ");
			   sql.append(" order by a.createTime desc") ;			   
			   SQLQuery query  = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());	           
			   return query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	        } catch (Exception e) {
	            log.error("queryHouseList fail",e);
	        }
	        return null;
	}
	
	public List<User> getAllAgreementList(Map<String, Object> param){
		StringBuffer sql =new StringBuffer();
		sql.append("from User where holdId="+Integer.valueOf(param.get("holdId").toString()));
		return null;
		
	}
	
	public Agreement getAgreementById(Map<String, Object> param){
		try {
			StringBuffer sql=new StringBuffer();
			sql.append("from Agreement where signPhone='"+param.get("phone").toString()+"'");
			Query q=entityManager.createQuery(sql.toString());
		return (Agreement) q.getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public List<Agreement> getAgreementList(Map<String, Object> param){
		List<Agreement> list=null;
		try {
			StringBuffer sql=new StringBuffer();
			sql.append("from Agreement where signUserId='"+param.get("signUserId").toString()+"' or chargeUserId='"+param.get("chargeUserId").toString()+"' and status='1' ");
			Query q=entityManager.createQuery(sql.toString());
			list=q.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}
